package org.sacgtug.android;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyActivity extends Activity {

	private static final String WEBVIEW_URL = "file:///android_asset/index.html";
	
	private WebView webView;
	
	private Handler mHandler = new Handler();
    
	@Override
    public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.main);
		
		final Intent myService = new Intent (this, MyService.class);
	    startService(myService);
	    
	    webView = (WebView) findViewById(R.id.webview);
		webView.getSettings().setJavaScriptEnabled(true);
		
		webView.setWebViewClient(new WebViewClient() {
			@Override
			public void onPageFinished(WebView view, String url) {
				
				Log.i("## A ##", "onPageFinished : url = " + url);
			}
		});
		
		webView.loadUrl(WEBVIEW_URL);
	}
	
	@Override
    public void onStart() {
    	super.onStart();

    }
    
    @Override
    public void onPause() {
    	super.onPause();
    	
    }
    
    
    @Override
    public void onNewIntent(Intent intent) {
    
    	Bundle extras = intent.getExtras();
    	
    	if(null != extras && extras.containsKey("location")) {
    		String location = extras.getString("location");
    		callJavaScriptFunction("showServiceResult", location);
    	}
    }
    
    private void callJavaScriptFunction(final String functionName, final String json) {

    	mHandler.post(new Runnable() {

    		public void run() {

    			Log.i("## A ##", "callJavaScriptFunction functionName = " + functionName + " : json = " +json);
    			
    			webView.loadUrl("javascript:" + functionName + "(" + json + ")");
    		}
    	});
    }
}
